package com.example.service.adm.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constants.ErrorMsg;
import com.example.context.PageResult;
import com.example.entity.ProductCateDO;
import com.example.exception.exception;
import com.example.mapper.ProductCateMapper;
import com.example.service.adm.AdmProductCateService;
import com.example.vo.cate.AdmProdCatePageReq;
import com.example.vo.cate.ProdCateReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdmProductCateServiceImpl extends ServiceImpl<ProductCateMapper, ProductCateDO>
        implements AdmProductCateService {
    @Override
    public PageResult<ProductCateDO> pageQuery(AdmProdCatePageReq req) {
        Page<ProductCateDO> page = new Page<>(req.getPage(), req.getSize());
        LambdaQueryWrapper<ProductCateDO> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getCateName())) {
            wrapper.like(ProductCateDO::getCateName, req.getCateName());
        }
        wrapper.orderByDesc(ProductCateDO::getCreateTime);
        page = page(page, wrapper);
        return PageResult.of(page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords());
    }

    @Override
    public void modify(ProdCateReq req) {
        if (req.getId() == null) {
            throw new exception("分类id不能为空");
        }
        LambdaQueryWrapper<ProductCateDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCateDO::getCateName, req.getCateName())
                .ne(ProductCateDO::getId, req.getId());
        if (count(wrapper) > 0) {
            throw new exception("分类名称已存在");
        }
        ProductCateDO cateDO = BeanUtil.toBean(req, ProductCateDO.class);
        if (!updateById(cateDO)) {
            throw new exception(ErrorMsg.UPDATE_FAILED);
        }
    }

    @Override
    public void add(ProdCateReq req) {
        LambdaQueryWrapper<ProductCateDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCateDO::getCateName, req.getCateName());
        if (count(wrapper) > 0) {
            throw new exception("分类名称已存在");
        }
        ProductCateDO cateDO = BeanUtil.toBean(req, ProductCateDO.class);
        if (!save(cateDO)) {
            throw new exception(ErrorMsg.INSERT_FAILED);
        }
    }

    @Override
    public void delete(Long[] idS) {
        this.removeByIds(List.of(idS));
    }

}
